package com.example.service;

import cn.hutool.core.date.DateUtil;
import com.example.entity.Busorders;
import com.example.entity.Busticket;
import com.example.entity.User;
import com.example.exception.CustomException;
import com.example.mapper.BusordersMapper;
import com.example.mapper.BusticketMapper;
import com.example.mapper.UserMapper;
import com.example.utils.TimeUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * 汽车票订单表业务处理
 **/
@Service
public class BusordersService {

    @Resource
    private BusordersMapper busordersMapper;
    @Resource
    private BusticketMapper busticketMapper;
    @Resource
    private UserMapper userMapper;

    /**
     * 新增
     */
    public void add(Busorders busorders) throws ParseException {
        busorders.setTime(DateUtil.now());
        busorders.setOrderNo(DateUtil.format(new Date(), "yyyyMMddHHmmss"));

        // 1. 判断一下车票的剩余数量
        Busticket busticket = busticketMapper.selectById(busorders.getTicketId());
        if (busticket.getNum() < busorders.getNum()) {
            throw new CustomException("-1", "当前车票数量不足");
        }
        // 2. 判断一下用户的余额够不够这个机票的费用
        Double price = busticket.getPrice() * busorders.getNum();
        User user = userMapper.selectById(busorders.getUserId());
        if (user.getAccount() < price) {
            throw new CustomException("-1", "您的余额不足，请到个人中心充值");
        }
        // 3. 判断一下当前天是否在起飞天之前
        String today = DateUtil.format(new Date(), "yyyy-MM-dd");
        if (TimeUtils.compareDate(today, busorders.getBegin(), "yyyy-MM-dd")) {
            throw new CustomException("-1", "平台限定最早只能预订第二天的票");
        }
        busorders.setFlyTime(busorders.getBegin() + " " + busticket.getStartTime());
        busordersMapper.insert(busorders);

        // 4. 扣除用户的余额
        user.setAccount(user.getAccount() - price);
        userMapper.updateById(user);
        // 5. 扣掉这个车票的剩余数量
        busticket.setNum(busticket.getNum() - busorders.getNum());
        busticketMapper.updateById(busticket);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        busordersMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            busordersMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(Busorders busorders) {
        busordersMapper.updateById(busorders);
    }

    /**
     * 根据ID查询
     */
    public Busorders selectById(Integer id) {
        return busordersMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<Busorders> selectAll(Busorders busorders) {
        List<Busorders> list = busordersMapper.selectAll(busorders);
        for (Busorders dbOrders : list) {
            dbOrders.setTotal(dbOrders.getPrice() * dbOrders.getNum());
        }
        return list;
    }

    /**
     * 分页查询
     */
    public PageInfo<Busorders> selectPage(Busorders busorders, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Busorders> list = busordersMapper.selectAll(busorders);
        return PageInfo.of(list);
    }

    /**
     * 退票功能
     */
    public void returnTicket(Busorders busorders) throws ParseException {
        // 1. 判断当前的时间是否已经过了起飞的时间
        String now = DateUtil.now();
        String flyTime = busorders.getFlyTime();
        if (!TimeUtils.compareDate(flyTime, now, "yyyy-MM-dd HH:mm:ss")) {
            throw new CustomException("-1", "您的车次已经出发，无法退票");
        }
        // 2. 退票
        busorders.setStatus("已退票");
        busordersMapper.updateById(busorders);
        // 3. 退钱
        User user = userMapper.selectById(busorders.getUserId());
        user.setAccount(user.getAccount() + busorders.getNum() * busorders.getPrice());
        userMapper.updateById(user);
        // 4. 票数返还
        Busticket busticket = busticketMapper.selectById(busorders.getTicketId());
        busticket.setNum(busticket.getNum() + busorders.getNum());
        busticketMapper.updateById(busticket);
    }

    /**
     * 改签功能
     */
    public void change(Busorders busorders) throws ParseException {
        // 获取今天的时间
        String today = DateUtil.format(new Date(), "yyyy-MM-dd");
        if (TimeUtils.compareDate(today, busorders.getBegin(), "yyyy-MM-dd")) {
            throw new CustomException("-1", "平台限定最早只能改签第二天的票");
        }
        // 计算一下是否需要补差价或者退差价
        User user = userMapper.selectById(busorders.getUserId());
        double price = busorders.getNum() * busorders.getPrice();
        Integer ticketId = busorders.getTicketId();
        Busticket busticket = busticketMapper.selectById(ticketId);
        double nowPrice = busticket.getPrice() * busorders.getNum();
        if (price < nowPrice) {
            double gap = nowPrice - price;
            if (user.getAccount() < gap) {
                throw new CustomException("-1", "您的余额不足，请到个人中心充值");
            } else {
                // 用户补差价
                user.setAccount(user.getAccount() - gap);
                userMapper.updateById(user);
            }
        }
        if (price > nowPrice) {
            double gap = price - nowPrice;
            // 平台退差价
            user.setAccount(user.getAccount() + gap);
            userMapper.updateById(user);
        }
        // 更新一下改签后的订单信息
        busorders.setName(busticket.getName());
        busorders.setFlyTime(busorders.getBegin() + " " + busticket.getStartTime());
        busorders.setStartAirport(busticket.getStartAirport());
        busorders.setEndAirport(busticket.getEndAirport());
        busorders.setTimeSlot(busticket.getTime());
        busorders.setPrice(busticket.getPrice());

        busordersMapper.updateById(busorders);
    }
}